package zut.DAO.impl;

import zut.DAO.OrderDAO;
import zut.DO.AuctionDO;
import zut.DO.OrderDO;
import zut.util.JDBCUtil;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class OrderDAOImpl implements OrderDAO {
    @Override
    public boolean addOrder(OrderDO order) {
        Connection connection = JDBCUtil.getConnction();
        String sql = "insert into orders (userid,totalprice,status,createtime ) values (?,?,?,?)";
        Date date = new java.util.Date();
//将时间格式转换成符合Timestamp要求的格式
        String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);

        Timestamp ts_date = Timestamp.valueOf(nowTime);
        try {
            assert connection != null;
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, order.getUserid());
            ps.setDouble(2, order.getTotalPrice());
            ps.setString(3, order.getStatus());
            ps.setTimestamp(4,ts_date);
            ps.execute();
            return true;
        } catch (SQLException throwables) {
            return false;
        }
    }

    @Override
    public List<OrderDO> findallbyid(String id) throws SQLException {
        List<OrderDO> orderList = new ArrayList<>();
        Connection connection = JDBCUtil.getConnction();
        String sql = "select * from orders where userid =?";
        assert connection != null;
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1,id);
        ResultSet rs = ps.executeQuery();
        while (rs.next()){
            String orderid = rs.getString("orderid");
            double totalprice = rs.getDouble("totalprice");
            String status = rs.getString("status");
            Date createtime = rs.getTimestamp("createtime");
            OrderDO o = new OrderDO(id,status,totalprice);
            o.setOrderid(orderid);
            o.setCreatetime(createtime);
            orderList.add(o);
        }
        return orderList;
    }

    @Override
    public boolean paysuccess(String status,String userid) {
        Connection connection = JDBCUtil.getConnction();
        String sql = "update orders set status = ? where orderid = ?";
        try {
            assert connection != null;
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1,status);
            ps.setString(2,userid);
            ps.execute();
            return true;
        } catch (SQLException throwables) {
            return false;
        }
    }
}


